import router, { asyncRoutes } from "@/router";
import store from "@/store";
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
const whiteList = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  // 开启页面加载条
  NProgress.start()
  const token = store.state.user.token // 查询令牌
  // console.log(token);
  if (token) {
    // 已登录
    console.log('已登录');
    if (to.path === '/login') {
      console.log('已登录,去首页');
      next('/')
      NProgress.done() // 页面加载条结束
    } else {
      console.log('在首页了,不管你');
      // console.log(store.state.user.userInfo);
      if (!store.state.user.userInfo.userId) {
        // 2. 调用vuex中的函数
        const menus = await store.dispatch('user/getUserInfo')
        console.log('menus', menus);
        // 筛选
        const filerRoutes = asyncRoutes.filter(item => {
          return menus.includes(item.children[0].name)
        })
        // 动态添加
        router.addRoutes(filerRoutes)
        // 最后添加404
        router.addRoutes([{ path: '*', redirect: '/404', hidden: true }])
        // 存vuex
        store.commit('menus/updateMenus', filerRoutes)
        // 解决动态白屏
        return next({ ...to, replace: true })
      }

      next()

    }
  } else {
    // 未登录
    console.log('未登录');
    if (whiteList.includes(to.path)) {
      console.log('未登录,在登录页,不管你');
      next()
    } else {
      console.log('未登录,不在别的页面,去登录');
      next('/login')
      NProgress.done() // 页面加载条结束
    }
  }
})
// 后置路由守卫
router.afterEach(() => {
  NProgress.done() // 页面加载条结束
})